package jp.gotenyama.android.widget.fusen;

import jp.gotenyama.widget.fusen.R;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;

public class MyFusenWidgetActivity extends Activity implements OnClickListener {
	EditText fusenText;
	Button registButton;

	private static final String TEXT_BODY = "memo";  
	SharedPreferences pref;  

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity);
		
		fusenText = (EditText) findViewById(R.id.fusenText);
		registButton = (Button) findViewById(R.id.registButton);
		
		registButton.setOnClickListener(this);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		//保存したメモテキスト取得
		pref = PreferenceManager.getDefaultSharedPreferences(this); 
		String memo = pref.getString(TEXT_BODY, "");
		fusenText.setText(memo);
	}

	public void onClick(View v) {
		if(v == registButton) {
			String textBody = fusenText.getText().toString();
			
            ComponentName thisWidget = new ComponentName(this, MyFusenWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            
            RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.main);
            remoteViews.setTextViewText(R.id.fusenTextView, textBody);
            
            //入力されたテキストをメモとして保存
            SharedPreferences.Editor editor = pref.edit();
            editor.putString(TEXT_BODY, textBody);
            editor.commit();
            
            //widgetへ反映
            manager.updateAppWidget(thisWidget, remoteViews);
            finish();
		}
	}
}
